// 成本过往排行
var numberFormate = iot.getNumberFormat("0");

var timeNotYearFormatMap = {
    'year': "%Y",
    'month': "%m",
    'day': "%m-%d",
    'hour': "%m-%d %H"
};

dev.action = function(resp,param){
    //获取工厂名称
    var factoryName = getFactoryName(param.workSpaceName);
    //是否算总还是单
    var totalOrSingle = param.selectType;
    if (totalOrSingle == null){
        totalOrSingle = "total";
    }
    var theTime = param.time;
    var workSpace = param.workSpace;
    var db = iot.db();
    var format;
    var resultData = {
        content : iot.list()
    };

    var theTimeNotYear =  '';
    if(theTime && theTime.length() > 4){
        theTimeNotYear = theTime.substring(5,theTime.length());
    }
    var timeType = iot.getTimeByFormat(theTime);
    format = timeNotYearFormatMap[timeType];
    var yieldId = getFactoryYieldId(factoryName)
    // 2019年之后的数据
    var after2019Result = db.qry("select DATE_FORMAT(dev_win.the_time,'%Y') yearIx,SUM(dev_win.dvalue) totalSum from iot_dev_data_win dev_win," +
        " (select * from energy_struc_prop where type = 2 and name = '成本' and energy_struc_id = "+ workSpace +") esp" +
        " where dev_win.dev_id = esp.dev_id and dev_win.data_type = esp.name" +
        " and DATE_FORMAT(dev_win.the_time,'" + format + "') like '%"+ theTimeNotYear +"%'" +
        // " and dev_win.the_time >= '2019'" +
        " group by yearIx ORDER BY totalSum DESC");
    //获取19年之后产量

    var after2019YieldResult = db.qry("select DATE_FORMAT(win.the_time,'%Y') yearIx,SUM(dvalue) totalSum \n" +
        "from iot_dev_data_win win\n" +
        "where " +
        "if("+ yieldId +" = 10687,win.data_type = '_PV产量' ,1=1)\n" +
        "and dev_id = "+ yieldId +" \n" +
        "and DATE_FORMAT(win.the_time,'" + format + "') like '%"+ theTimeNotYear +"%'\n" +
        // "and win.the_time >= '2019'\n" +
        "group by yearIx ORDER BY totalSum DESC");

    /*// 计算2019年之前的数据，工厂  E001._用量*0.64 +  G001.用量*3.6
    var electricityResult = null;
    var gasResult = null;
    // 只过滤2019年之前的数据
    if(frameworkIdToDevSn[factoryName] && frameworkIdToDevSn[factoryName][workSpace].ele){
        electricityResult = db.qry("select DATE_FORMAT(win.the_time,'%Y') yearIx, SUM(win.dvalue) totalSum " +
            " FROM iot_dev_data_win win " +
            " LEFT JOIN iot_dev dev on dev.id = win.dev_id " +
            " where dev.sn='"+frameworkIdToDevSn[factoryName][workSpace].ele+"'" +
            " and win.data_type = '_用量'" +
            " and win.the_time < '2019'" +
            " and DATE_FORMAT(win.the_time,'" + format + "') like '%"+ theTimeNotYear +"%'" +
            " group by yearIx ORDER BY totalSum DESC");
    }

    if(frameworkIdToDevSn[factoryName] && frameworkIdToDevSn[factoryName][workSpace].gas){
        gasResult = db.qry("select DATE_FORMAT(win.the_time,'%Y') yearIx, SUM(win.dvalue) totalSum " +
            " FROM iot_dev_data_win win " +
            " LEFT JOIN iot_dev dev on dev.id = win.dev_id " +
            " where dev.sn = '"+ frameworkIdToDevSn[factoryName][workSpace].gas +"'" +
            " and win.the_time < '2019'" +
            " and DATE_FORMAT(win.the_time,'" + format + "') like '%"+ theTimeNotYear +"%'" +
            " group by yearIx ORDER BY totalSum DESC");
    }

    //获取19年之前产量
    var before2019YieldResult = db.qry("select DATE_FORMAT(win.the_time,'%Y') yearIx,SUM(dvalue) totalSum \n" +
        "from iot_dev_data_win win\n" +
        "where dev_id = "+ yieldId +" \n" +
        "and DATE_FORMAT(win.the_time,'" + format + "') like '%"+ theTimeNotYear +"%'\n" +
        "and win.the_time < '2019'\n" +
        "group by yearIx ORDER BY totalSum DESC");*/

    var sortList = iot.list();
    /*// 遍历添加2019年之前的数据

    var eleLength = 0;
    var gasLength = 0;
    var longData;
    var shortData;
    if (electricityResult != null){
        electricityResult.forAll(function () {
            eleLength ++;
        })
    }
    if (gasResult != null){
        gasResult.forAll(function () {
            gasLength ++;
        })
    }
    var maxLength = Math.max(eleLength, gasLength)

    if (eleLength === maxLength){
        longData = electricityResult;
        shortData = gasResult;
    } else {
        longData = gasResult;
        shortData = electricityResult;
    }


    if (longData != null || shortData != null) { // 电和燃气至少一个有数据，计算才有意义
        longData.forAll(function (longItem) {
            var totalSum = 0;
            var totalYield = 0;
            totalSum = (longItem.totalSum * (costTimeModulus[factoryName] && costTimeModulus[factoryName][longItem.yearIx] ? costTimeModulus[factoryName][longItem.yearIx].ele : 0));
            shortData.forAll(function (shortItem) {
                if (longItem.yearIx.equals(shortItem.yearIx)) {
                    totalSum += shortItem.totalSum * (costTimeModulus[factoryName] && costTimeModulus[factoryName][shortItem.yearIx] ? costTimeModulus[factoryName][shortItem.yearIx].gas : 0);
                }
            })
            if (before2019YieldResult) {
                before2019YieldResult.forAll(function (yieldItem) {
                    if (longItem.yearIx.equals(yieldItem.yearIx)) {
                        totalYield = yieldItem.totalSum;
                    }
                });
            }
            //判断当前选择总数还是单车
            if (totalOrSingle.equals("single")) {
                if (totalYield) {
                    totalSum = totalSum / totalYield;
                }
                if (totalYield === 0) {
                    totalSum = 0;
                }
            }
            sortList.add({year: longItem.yearIx, totalSum: totalSum});
        })
    }*/

    /*if (electricityResult != null || gasResult != null) { // 电和燃气至少一个有数据，计算才有意义
        // 电和燃气都不为空，计算两者的和
        if (electricityResult != null && gasResult != null) {
            electricityResult.forAll(function (electrItem) {
                var totalSum = 0;
                var totalYield = 0;
                gasResult.forAll(function (gasItem) {
                    if (electrItem.yearIx.equals(gasItem.yearIx)) {
                        totalSum = (electrItem.totalSum * 0.64) + (gasItem.totalSum * 3.6);
                        before2019YieldResult.forAll(function (yieldItem) {
                            if (electrItem.yearIx.equals(yieldItem.yearIx)) {
                                totalYield = yieldItem.totalSum;
                            }
                        });
                        //如果当前选择是单车
                        if (totalOrSingle.equals("single")) {
                            if (totalYield != 0) {
                                totalSum = totalSum / totalYield;
                            } else {
                                totalSum = 0;
                            }
                        }
                    }
                })
                sortList.add({year: electrItem.yearIx, totalSum: totalSum});
            })
        }
        // 电不为空，燃气为空，计算电的数据
        if (electricityResult != null && gasResult == null) {
            electricityResult.forAll(function (electrItem) {
                var totalSum = electrItem.totalSum * 0.64;
                var totalYield = 0;
                before2019YieldResult.forAll(function (yieldItem) {
                    if (electrItem.yearIx.equals(yieldItem.yearIx)) {
                        totalYield = yieldItem.totalSum;
                    }
                });
                //如果当前选择是单车
                if (totalOrSingle.equals("single")) {
                    if (totalYield != 0) {
                        totalSum = totalSum / totalYield;
                    } else {
                        totalSum = 0;
                    }
                }
                sortList.add({year: electrItem.yearIx, totalSum: totalSum});
            })
        }
        // 电为空，燃气不为空，计算燃气的数据
        if (electricityResult == null && gasResult != null) {
            gasResult.forAll(function (gasItem) {
                var totalSum = gasItem.totalSum * 3.6;
                var totalYield = 0;
                before2019YieldResult.forAll(function (yieldItem) {
                    if (gasItem.yearIx.equals(yieldItem.yearIx)) {
                        totalYield = yieldItem.totalSum;
                    }
                });
                //如果当前选择是单车
                if (totalOrSingle.equals("single")) {
                    if (totalYield != 0) {
                        totalSum = totalSum / totalYield;
                    } else {
                        totalSum = 0;
                    }
                }
                sortList.add({year: gasItem.yearIx, totalSum: totalSum});
            });
        }
    }*/

    // 添加2019年之后的数据
    if (after2019Result != null) {
        var after2019Sum = 0;
        after2019Result.forAll(function (item) {
            if (item.totalSum) {
                after2019Sum = item.totalSum;
            }
            var totalYield = 0;
            if (after2019YieldResult != null){
                after2019YieldResult.forAll(function (yieldItem) {
                    if (yieldItem.yearIx.equals(item.yearIx)) {
                        totalYield = yieldItem.totalSum;
                    }
                });
            }
            //判断当前选择总数还是单车
            if (totalOrSingle.equals("single")) {
                if (totalYield != 0){
                    after2019Sum = after2019Sum / totalYield;
                } else {
                    after2019Sum = 0;
                }
            }
            sortList.add({year: item.yearIx, totalSum: after2019Sum});
        })
    }

    // JS调用Java排序方法，对sortList根据totalSum进行降序排列
    var Collections = Java.type("java.util.Collections");
    var Comparator = Java.type("java.util.Comparator")
    var Printer = Java.extend(Comparator, {
        compare : function (o1, o2) {
            if (o1.totalSum > o2.totalSum) {
                return -1;
            }
            if (o2.totalSum > o1.totalSum) {
                return 1;
            }
            return 0;
        }
    })
    Collections.sort(sortList, new Printer());

    var count = 0;
    var preValue = "";
    var resultList = iot.list();
    var timeDataList = getNearlyFourYears(param.time);
    // 开始组装数据
    for (var i in sortList) {
        // 只有数值不一样，排名才会上升，将当前值赋值给preValue
        if (!sortList[i].totalSum.equals(preValue)) {
            preValue = sortList[i].totalSum;
            ++count;
        }
        var useNum = numberFormate.format(sortList[i].totalSum);
        resultList.add({rank: count, year: sortList[i].year, useNum: useNum, increase: "0%"});
    }

    // 如果没有timeDataList年份的数据，则赋值为0
    for (var i in timeDataList) {
        var flag = false;
        for (var key in resultList) {
            if (resultList[key].year.equals(timeDataList[i])) {
                flag = true;
            }
        }
        if (!flag) {
            resultList.add({rank: count + 1, year: timeDataList[i], useNum: 0, increase: "0%"});
        }
    }
    // 计算同比年/月/日涨幅
    var increaseList = iot.list();
    for (var i in timeDataList) {
        if (i == 0) { // 第一年没有同比涨幅
            continue;
        }
        var currentUseNum = 0, preUseNum = 0; // 存储当前年份总量和同比时间的总量
        for (var j in resultList) {
            if (timeDataList[i].equals(resultList[j].year)) {
                currentUseNum = resultList[j].useNum;
            }
            if (timeDataList[i - 1].equals(resultList[j].year)) {
                preUseNum = resultList[j].useNum;
            }
        }
        if (currentUseNum == 0 || preUseNum == 0) { // 只要有一年的总量为0，则计算涨幅没有意义
            continue;
        }
        var increase = (currentUseNum - preUseNum) / preUseNum; // 计算同比涨幅
        var toFixedIncrease = (100 * increase).toFixed(2); // 保留两位小数
        increaseList.add({year: timeDataList[i], increase: toFixedIncrease + "%"})
    }

    // 修改同比涨幅
    for (var i in resultList) {
        // 开始遍历修改resultList的同比涨幅increase
        var flag = false;
        var increase;
        for (var j in increaseList) {
            if (resultList[i].year.equals(increaseList[j].year)) {
                flag = true;
                increase = increaseList[j].increase;
            }
        }
        if (flag) {
            resultList[i].increase = increase;
        }
    }
    // 把时间格式转换成和参数：theTime一样
    /*for (var i in resultList) {
        resultList[i].year = getTime(resultList[i].year, theTime);
    }*/

    resultData.content = resultList;
    resp.setJsData(resultData);

}